package com.youdu.vuandroidadsdk.okhttp;

import com.youdu.vuandroidadsdk.okhttp.https.HttpsUtils;
import com.youdu.vuandroidadsdk.okhttp.listener.DisposeDataHandle;
import com.youdu.vuandroidadsdk.okhttp.response.CommonFileCallback;
import com.youdu.vuandroidadsdk.okhttp.response.CommonJsonCallback;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * @Title:CommonHttpClient
 * @Package:com.youdu.vuandroidadsdk.okhttp
 * @Description: 1,请求的发送；2，请求参数的配置；3，https的支持；
 * @Auther:YJH
 * @Email:yuannunhua@gmail.com
 * @Date:2018/7/2312:45
 */
public class CommonHttpClient {

    private static final int TIME_OUT = 30;
    private static OkHttpClient mOkHttpClient;

    //创建client对象的构建者；并为构建者设置超时时间；
    static {
        OkHttpClient.Builder okHttpClentBuilder = new OkHttpClient.Builder();

        okHttpClentBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpClentBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpClentBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);

        okHttpClentBuilder.followRedirects(true);//允许重定向

        //https 的支持
        okHttpClentBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        okHttpClentBuilder.sslSocketFactory(HttpsUtils.initSSLSocketFactory());


        mOkHttpClient = okHttpClentBuilder.build();

    }


    /**
     * 通过构造好的Request,Callback去发送请求
     *
     * @param request
     * @param handle
     */
    public static Call get(Request request, DisposeDataHandle handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handle));
        return call;
    }

    public static Call post(Request request, DisposeDataHandle handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonJsonCallback(handle));
        return call;
    }

    public static Call downloadFile(Request request, DisposeDataHandle handle) {
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new CommonFileCallback(handle));
        return call;
    }
}
